package com.wu.demo.fileupload.demo.controller;

import com.wu.demo.fileupload.demo.service.IImgUploadService;
import com.wu.demo.fileupload.demo.util.FileUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@MapperScan("com.autumn.mapper")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger("TestController.class");
    private final ResourceLoader resourceLoader;
    @Autowired
    private IImgUploadService iImgUploadService;
    @Value("${web.upload-path}")
    private String path;
    @Value("${server.port}")
    private String port;

    @Autowired
    public TestController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * @param file 要上传的文件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public Map<String, String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        Map<String,String>  map=new HashMap<>();

        String filePath = request.getSession().getServletContext().getRealPath(path);

        //生成随机字符串，用于图片命名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 获得文件类型
        String fileType = file.getContentType();
        // 获得文件后缀名称
        String imageName = fileType.substring(fileType.indexOf("/") + 1);
        // 原名称
//        String fileName = file.getOriginalFilename();
        // 新名称
        String newFileName = uuid + "." + imageName;

        System.out.println(imageName);

        try {
            FileUtils.upload(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 拼接图片url
        String imgHost = "http://127.0.0.1:" + port;
        String imgUploadPath = path;
        String imgName = newFileName;
        String imgPath = imgHost + imgUploadPath + imgName;
        iImgUploadService.imgUpload(imgPath);
        map.put("url",imgPath);
        return map;

    }

    /**
     * 跳转到文件上传页面
     *
     * @return
     */
    @RequestMapping("test")
    public String toUpload() {
        return "ttt";
    }

}
